<?php
/***
 * 赠品后台控制器
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */


namespace App\Http\Controllers\Backstage;

use App\Services\BrandService\BrandToolService;
use App\Services\GiftService\GiftTool;
use App\Services\ImgServices\ImgTool;
use App\Services\ProductTempService\ProductTempTool;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use App\Services\GiftService\GiftBackService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class GiftControllers extends Controller
{
    protected $giftBackService;
    protected $imgTool;
    protected $productTempTool;
    /**
     * GiftControllers constructor.
     */
    public function __construct(GiftBackService $giftBackService,
                                   ProductTempTool $productTempTool,
                                ImgTool $imgTool)
    {
        $this->giftBackService=$giftBackService;
        $this->imgTool=$imgTool;
        $this->productTempTool=$productTempTool;
    }

    /**
     * 赠品搜索
     * @param Request $request
     * @return array
     */
    public function postGiftSearch(Request $request){
        $v=array(
            'keyword'=>'required|string'
        );
        $validator=$this->giftBackService->store($request,$v);
        if ($validator->fails())
        {
            if ($validator->errors()->first('keyword')) {
                $keyword='';
            }
        }else{
            $keyword=trim($request->input('keyword'));
        }
        $data=$this->giftBackService->SearchGifts($keyword);
        return array('message'=>'成功','data'=>$data,'state'=>'M00000');
    }
    /**
     * 添加赠品页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getAddGift(Request $request)
    {
        return view('backstage.gift.addGift');
    }

    /**
     * 添加赠品
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function postAddGift(Request $request)
    {
        $v = [
            'gift_name' => 'required|string|max:90',
            'date-range-picker' => 'required|string|',
            'image'=>'required|image',
        ];
        $validator=$this->giftBackService->store($request,$v);
        $param_desc=trim($request->input('param_desc'));
        $gift_desc=trim($request->input('gift_desc'));
        $date_range_picker=trim($request->input('date-range-picker'));
        $data=array();
        $data['param_desc']=$param_desc;
        $data['gift_desc']=$gift_desc;
        if(!empty($date_range_picker)){
            $time_arr=explode("-",$date_range_picker);
            $preferential_begin_time=strtotime($time_arr[0]);
            $preferential_end_time  =strtotime($time_arr[1])+86400-1;
            $data['begin_time']=$preferential_begin_time;
            $data['end_time']=$preferential_end_time;
        }
        $validator->after(function($validator) use ($data) {
            $param_desc_l=mb_strlen($data['param_desc'],'utf-8');
            if ($param_desc_l>250) {
                $validator->errors()->add('param_desc','简介太长');
            }
            $gift_desc_l=mb_strlen($data['gift_desc'],'utf-8');
            if ($gift_desc_l>250) {
                $validator->errors()->add('gift_desc','简介太长');
            }
            if ($data['end_time']<=time()) {
                $validator->errors()->add('date-range-picker','请重新选择时间');
            }
        });
        if ($validator->fails())
        {
            $request->flash();
            return redirect()->back()->withErrors($validator->errors())->withInput();
        }
        $gift=array();
        $gift['name']=trim($request->input('gift_name'));
        $gift['image']=$request->file('image');
        $gift['param_desc']=$param_desc;
        $gift['gift_desc']=$gift_desc;
        $gift['end_time']=$data['end_time'];
        $gift['begin_time']=$data['begin_time'];
        $res=$this->giftBackService->addGift($gift);
        if($res){
            return redirect()->back()->with('success_message', '添加成功!');
        }else{
            return redirect()->back()->with('error_message', '添加失败!');
        }
    }
    /**
     * 赠品详情
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getGiftUpdate(Request $request)
    {
        $v = [
            'gift_id' => 'required|integer|min:0',
        ];
        $validator=$this->giftBackService->store($request,$v);
        $id=intval($request->input('gift_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('gift_id')){
                if(!empty($page)){
                    return redirect()->back()->with('error_message', '无法获取编号!');
                }
            }
        }
        $gift=$this->giftBackService->getGiftDetailById($id,1);
        if(empty($gift)){
            return redirect()->back()->with('error_message', '该赠品不存在!');
        }
        $gift->thumbnail=ImgTool::getImgUrlByImgPath($gift->thumbnail);
        $gift->original_image=ImgTool::getImgUrlByImgPath($gift->original_image);
        return view('backstage.gift.giftUpdate')->with('gift',$gift);
    }

    /**
     * 赠品更新
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postGiftUpdate(Request $request)
    {
        $v = [
            'gift_id' => 'required|integer|min:0',
        ];
        $validator=$this->giftBackService->store($request,$v);
        $id=intval($request->input('gift_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('gift_id')){
                return redirect()->back()->with('error_message', '无法获取编号!');
            }
        }
        $gift=$this->giftBackService->getGiftDetailById($id);
        if(empty($gift)||($gift->state!=1)){
            return redirect()->back()->with('error_message', '该赠品不存在!');
        }
        $gift_update=array();
        $gift_update['id']=$id;
        $gift_update['name']=trim($request->input('gift_name'));
        $param_desc=trim($request->input('param_desc'));
        $gift_desc=trim($request->input('gift_desc'));
        $gift_update['param_desc']=$param_desc;
        $gift_update['gift_desc']=$gift_desc;
        $date_range_picker=trim($request->input('date-range-picker'));
        if(!empty($date_range_picker)){
            $time_arr=explode("-",$date_range_picker);
            $preferential_begin_time=strtotime($time_arr[0]);
            $preferential_end_time  =strtotime($time_arr[1])+86400-1;
            $gift_update['begin_time']=$preferential_begin_time;
            $gift_update['end_time']=$preferential_end_time;
        }
        $param_desc_l=mb_strlen($param_desc,'utf-8');
        if ($param_desc_l>250) {
            return redirect()->back()->with('error_message','参数简介太长');
        }
        $gift_desc_l=mb_strlen($gift_desc,'utf-8');
        if ($gift_desc_l>250) {
            return redirect()->back()->with('error_message','赠品简介太长');
        }
        if ($gift_update['end_time']<time()) {
            return redirect()->back()->with('error_message','时间错误');
        }
        $image=$request->file('image');
        if(Input::hasFile('image')){
            $save_path=$this->imgTool->imgSave($image,2);
            $image_thumb=$this->imgTool->getImgThumbByImgPath($save_path,300,300);
            $gift_update['original_image']=empty($save_path)?'':$save_path;
            $gift_update['thumbnail']=empty($image_thumb)?'':$image_thumb;
        }
        $res=$this->giftBackService->giftUpdate($gift_update);
        if($res==1){
            return redirect()->back()->with('success_message', '更新成功!');
        }else{
            return redirect()->back()->with('error_message', '更新失败!');
        }
    }

    /**
     * 删除赠品
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postDeleteGift(Request $request)
    {
        $v = [
            'gift_id' => 'required|integer|min:0',
        ];
        $validator=$this->giftBackService->store($request,$v);
        $id=intval($request->input('gift_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('gift_id')){
                $result["state"] = -1;
                $result["message"] = "无法获取赠品id";
                return response()->json($result);
            }
        }
        $gift=$this->giftBackService->getGiftDetailById($id);
        if(empty($gift)||($gift->state!=1)){
            $result["state"] = -2;
            $result["message"] = "赠品不存在";
            return response()->json($result);
        }
        $res=$this->giftBackService->giftDelete($id);
        if($res==1){
            $result["state"] = 1;
            $result["message"] = "删除成功";
            return response()->json($result);
        }else{
            $result["state"] = -3;
            $result["message"] = "删除失败";
            return response()->json($result);
        }
    }
    /**
     * 赠品列表
     * @param Request $request
     * @return $this
     */
    public function getGiftList(Request $request)
    {
        $v = [
            'page' => 'required|integer|min:0',
        ];
        $validator=$this->giftBackService->store($request,$v);
        $page=intval($request->input('page'));
        if ($validator->fails())
        {
            if($validator->errors()->first('page')){
                if(!empty($page)){
                    return redirect('/backstage/gift/gift-list');
                }
            }
        }
        $gifts=$this->giftBackService->getGiftList();
        return view('backstage.gift.giftList')->with('gifts',$gifts);
    }

    /**
     * 赠品使用范围页面
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getGiftUseRange(Request $request){
        $rules=array(
            'gift_id' => 'required|integer|min:0'
        );
        $validator=$this->giftBackService->store($request,$rules);
        $gift_id=intval($request->input('gift_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('gift_id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }
        }
        $gift=$this->giftBackService->getGiftById($gift_id);
        if(empty($gift)||($gift->state!=1)){
            return redirect()->back()->with('error_message', '赠品不存在!');
        }
        $already_binding_product_temp_ids=array();
        $already_binding_brand_ids=array();
        $favorable_gifts=GiftTool::getSimpleRegsByGiftId($gift_id,1);
        foreach ($favorable_gifts as $favorable_gift){
            if($favorable_gift->type===1){
                $already_binding_product_temp_ids[]=$favorable_gift->reg_id;
            }
            if($favorable_gift->type===3){
                $already_binding_brand_ids[]=$favorable_gift->reg_id;
            }
        }
        $product_temps=$this->productTempTool->getProductTempsByProductTempIds($already_binding_product_temp_ids);
        $brands=BrandToolService::getBrandsWhereNotInBrandIds($already_binding_brand_ids);
        $fav_gifts=$this->giftBackService->getFavorableGiftsByGiftId($gift->id);
        return view('backstage.gift.giftUseRangeList')->with("gift",$gift)
                   ->with("product_temps",$product_temps)
                   ->with("brands",$brands)
                   ->with("gift",$gift)
                   ->with('fav_gifts',$fav_gifts);
    }

    /**
     * 添加赠品优惠范围绑定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
     public function addGiftMap(Request $request){
         Log::info($request->all());
         $rule=array(
             'gift_id'=>'required|integer|min:1',
             'gift_type'=>'required|string|',
             'resource_id'=>'required|string|min:1',
         );
         $gift_id=intval($request->input('gift_id'));
         $gift_type=trim($request->input('gift_type'));
         $resource_id=trim($request->input('resource_id'));
         $validator=ProductTempTool::store($request,$rule);
         $data['gift_id']=$gift_id;
         $data['reg_id']=$resource_id;
         if ($validator->fails())
         {
             if($validator->errors()->first('gift_id')){
                 $result['state']=-2;
                 $result['message']=' 赠品Id格式错误';
             }
             if($validator->errors()->first('gift_type')){
                 $result['state']=-3;
                 $result['message']='适用范围类型错误';
             }
             if($validator->errors()->first('resource_id')){
                 $result['state']=-4;
                 $result['message']='资源Id格式错误';
             }
             if(!empty($result)){
                 return response()->json($result);
             }
         }
         $flag=false;
         //判断绑定资源是不是存在
         $data['type']=-1;
         switch ($gift_type){
             case 'sel_quota':
                 $data['type']=0;
                 $flag=true;
                 break;
             //产品模板
             case 'sel_prod_temp':
                 $flag=ProductTempTool::productTempExistsByProdTempId($resource_id);
                 $data['type']=1;
                 break;
             case 'sel_prod':
                 $data['type']=2;
                 $flag=$this->giftBackService->productExistByProductId($resource_id);
                 //产品
                 break;
             case 'sel_brand':
                 $data['type']=3;
                 //品牌
                 $flag=BrandToolService::brandExistByBrandId($resource_id);
                 break;
             default :
                 break;

         }
         if($data['type']===-1){
             $result['state']=-5;
             $result['message']='绑定资源类型错误';
             return response()->json($result);
         }
         if($flag===false){
             $result['state']=-5;
             $result['message']='绑定资源不存在';
             return response()->json($result);
         }
         $exist=$this->giftBackService->regIdHasBindingGiftId($gift_id,$resource_id,$gift_type,1);
         Log::info('是否绑定过：'.$exist);
         if($exist){
             $result['state']=1;
             $result['message']='保存成功';
             return response()->json($result);
         }
         $res=$this->giftBackService->addGiftMap($data);
         if($res){
             $result['state']=1;
             $result['message']='保存成功';
         }else{
             $result['state']=-1;
             $result['message']='保存失败';
         }
         return response()->json($result);
     }
    /**
     *赠品使用详情
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getGiftUseRangeDetails(Request $request){
        $rules=array(
            'gift_id' => 'required|integer|min:0'
        );
        $validator=$this->giftBackService->store($request,$rules);
        $gift_id=intval($request->input('gift_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('gift_id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }
        }
        $gift=$this->giftBackService->getGiftById($gift_id);
        if(empty($gift)||($gift->state!=1)){
            return redirect()->back()->with('error_message', '赠品不存在!');
        }
        $fav_gifts=$this->giftBackService->getFavorableAllGiftsByGiftId($gift->id);
        return view('backstage.gift.giftUseRangeDetail')->with("gift",$gift)
                                                        ->with('fav_gifts',$fav_gifts);
    }

    /**
     * 赠品使用记录删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postFavGiftDelete(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->giftBackService->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
        }
        $id=intval($request->input('id'));
        $channel=$this->giftBackService->favorableGiftDelete($id);
        if($channel){
            $result["state"] = 1;
            $result["message"] = "删除成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "删除失败";
            return response()->json($result);
        }
    }

    /**
     * 更新库存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUpdateStock(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
            'num' => 'required|integer|min:0'
        );
        $validator=$this->giftBackService->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
        }
        $id=intval($request->input('id'));
        $num=intval($request->input('num'));
        $res=$this->giftBackService->updateStock($id,$num);
        if($res){
            $result["state"] = 1;
            $result["message"] = "更新成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "更新失败";
            return response()->json($result);
        }
    }

    /**
     * 更新优惠资源，对应满订单额度时，赠送对应赠品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUpdateQuota(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
            'quota' => 'required|Numeric|min:0'
        );
        $validator=$this->giftBackService->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
            if($validator->errors()->first('quota')){
                $result["state"] = -3;
                $result["message"] = "金额格式不对";
                return response()->json($result);
            }
        }
        $id=intval($request->input('id'));
        //订单额度
        $quota=doubleval($request->input('quota'));
        $res=$this->giftBackService->updateQuota($id,$quota);
        if($res){
            $result["state"] = 1;
            $result["message"] = "更新成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "更新失败";
            return response()->json($result);
        }
    }
    /**
     * 更新赠品对应优惠资源使用时间
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postUpdateGiftUseTime(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
            'use_time' => 'required|string'
        );
        $validator=$this->giftBackService->store($request,$rules);
        $id=intval($request->input('id'));
        $date_range = trim($request->input('use_time'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -2;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
            if($validator->errors()->first('use_time')){
                $result["state"] = -3;
                $result["message"] = "时间格式不正确";
                return response()->json($result);
            }
        }
        if(!empty($date_range)){
            $time_arr=explode("-",$date_range);
            $begin_time=strtotime($time_arr[0]);
            $end_time  =strtotime($time_arr[1])+86400-1;
            $gift['begin_time']=$begin_time;
            $gift['end_time']=$end_time;
        }
        $gift['id']=$id;
        $res=$this->giftBackService->updateGiftUseTime($gift);
        if($res){
            $result["state"] = 1;
            $result["message"] = "更新成功";
            return response()->json($result);
        }else{
            $result["state"] = -1;
            $result["message"] = "更新失败";
            return response()->json($result);
        }
    }

    /**
     * 赠品对应资源搜索
     * @param Request $request
     * @return array
     */
    public function postResSearch(Request $request){
        $v=array(
            'keyword'=>'required|string',
            'range_type'=>'required|integer|min:0'
        );
        $validator=$this->giftBackService->store($request,$v);
        if ($validator->fails())
        {
            if ($validator->errors()->first('keyword')) {
                $keyword='';
            }
            if ($validator->errors()->first('range_type')) {
                $result["state"] = -2;
                $result["message"] = "搜索范围出错";
                return response()->json($result);
            }
        }else{
            $keyword=trim($request->input('keyword'));
        }
        $range_type=intval(trim($request->input('range_type')));
        switch ($range_type){
            case 1:
                $data=$this->giftBackService->SearchProductTemps($keyword);
                break;
            case 2:
                $data=$this->giftBackService->SearchProducts($keyword);
                break;
            case 3:
                $data=$this->giftBackService->SearchBrands($keyword);
                break;
            default:
                $data=array();
                break;
        }
        return array('message'=>'成功','data'=>$data,'state'=>'M00000');
    }
}